package com.cloudwave.trailends.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.adapter.OnDeleteAdapterItemListener;
import com.cloudwave.trailends.adapter.RidingLineListAdapter;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.service.RidingService;
import com.cloudwave.trailends.service.SyncService;
import com.cloudwave.trailends.utils.CollectionUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

/**
 * 
 * @author DolphinBoy 骑行历史列表
 * @email 569141948@qq.com
 * @date 2014-5-1
 * @time 下午10:04:28
 * 离线数据同步
 * http://www.douban.com/note/322822457/?type=like
 */

public class HistoryActivity extends BaseActivity {
	private final static String TAG = "HistoryActivity";
	
	private ImageButton btnBack;
  	private ImageButton btnOK;
  	private TextView tvTitle;
  	
  	private View rlEmptyView;
  	private TextView tvEmptyDownload;
  	private TextView tvEmptyStartRiding;
  	
  	
	private ListView lvHistoryList;
	private List<RidingLine> tList = null;
	private RidingLineListAdapter tListAdapter = null;
	
//	private String lastRefTime;
	
	private Animation rotateAnimation = null;
	
	private RidingReceiver ridingReceiver;
	private SyncReceiver syncReceiver;
	
	private RidingLine nowRidingLine = null;
	
//	private int downloadCount = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.history_simple);
		
		initView();
		
		checkNow();
		
		initListView();
		
		loadLocalData();
	}

	private void initView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		btnOK = (ImageButton) findViewById(R.id.btnOK);
		btnOK.setImageResource(R.drawable.img_actionitem_sync);
		
		rlEmptyView = (View) findViewById(R.id.rlEmptyView);
		
		tvEmptyDownload = (TextView) findViewById(R.id.tvEmptyDownload);
	  	tvEmptyStartRiding = (TextView) findViewById(R.id.tvEmptyStartRiding);
	  	
		btnOK.setVisibility(View.VISIBLE);
		tvTitle.setText("历史记录");
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				HistoryActivity.this.finish();
			}
		});
		btnOK.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rotateAnimation = AnimationUtils.loadAnimation(HistoryActivity.this, R.anim.rotate_anim);
				btnOK.startAnimation(rotateAnimation);
				dealSyncData();
			}
		});
		
		tvEmptyDownload.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				rotateAnimation = AnimationUtils.loadAnimation(HistoryActivity.this, R.anim.rotate_anim);
				btnOK.startAnimation(rotateAnimation);
				dealSyncData();
			}
		});
		tvEmptyStartRiding.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				HistoryActivity.this.finish();
			}
		});
		
	}

	private void checkNow() {
		DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		try {
			dbu.execNonQuery("update te_ridingline set isNow_ = 0 where isNow_ = 1");
		} catch (DbException e) {
			Log.e(TAG, e.getMessage());
		}
	}
	
	private void initListView() {
		tList = new ArrayList<RidingLine>();
		
		lvHistoryList = (ListView) findViewById(R.id.lvHistoryList);
		
		//当使用了OnTouchListener事件之后这个事件就没效果了
		lvHistoryList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				RidingLine t = tList.get(position);
				Intent intent = new Intent(HistoryActivity.this, DetailActivity.class);
				intent.putExtra("rlId", t.getId());
				startActivityForResult(intent, 201);
			}
		});
		
		tListAdapter = new RidingLineListAdapter(this, tList);
		lvHistoryList.setAdapter(tListAdapter);
		
		tListAdapter.setOnDeleteAdapterItemListener(new OnDeleteAdapterItemListener() {
			
			@Override
			public void onDelete(View view, int position, Object objId, boolean isSuccess) {
				if ( isSuccess ) {
					tList.remove(position);
					tListAdapter.notifyDataSetChanged();
				}
			}
		});
	}

	 @Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if ( RESULT_OK == resultCode ) {
			loadLocalData();
		}
    }
	 
	private void loadLocalData() {
		tList.clear();
		DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		Long userId = ((AppContext) getApplication()).getUid();
		try {
			long rlId = RidingService.now_rlId;
			if ( rlId != 0 ) {
				List<RidingLine> tTmpList = dbu.findAll(Selector.from(RidingLine.class).where("crudStatus_", "!=", "3").and("id_", "!=", rlId).orderBy("startTime_", true));
				if (CollectionUtils.isNotEmpty(tTmpList)) {
					tList.addAll(tTmpList);
				}
				
				nowRidingLine = dbu.findById(RidingLine.class, rlId);
				
				if ( nowRidingLine != null ) {
					nowRidingLine.setIsNow(true);
					tList.add(0, nowRidingLine);
				}
			} else {
				Selector selector = Selector.from(RidingLine.class).where("crudStatus_", "!=", "3");
				if ( userId != null ) {
					selector.where("creator_id", "==", userId).or("creator_id", "==", null);
				}
				selector.orderBy("startTime_", true);
				List<RidingLine> tTmpList = dbu.findAll(selector);
				if (CollectionUtils.isNotEmpty(tTmpList)) {
					tList.addAll(tTmpList);
				}
			}
			
			if ( CollectionUtils.isEmpty(tList) ) {
				rlEmptyView.setVisibility(View.VISIBLE);
				lvHistoryList.setVisibility(View.GONE);
			} else {
				rlEmptyView.setVisibility(View.GONE);
				lvHistoryList.setVisibility(View.VISIBLE);
				tListAdapter.notifyDataSetChanged();
			}
		} catch (DbException e) {
			Toast.makeText(HistoryActivity.this, "加载骑行记录失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}

	private void dealSyncData() {
//		String className = "com.cloudwave.trailends.service.SyncService";
//		if ( !AppContext.isServiceRunning(HistoryActivity.this, className) ) {
//			Log.i(TAG, "["+className+"]服务没有运行!");
//			Intent intent = new Intent();
//			intent.setAction(SyncService.SYNC_SERVICE);
//			startService(intent);
//		} else {
//			Intent intent = new Intent();
//			intent.setAction(SyncService.SYNC_SERVICE);
//			startService(intent);
//		}
		
		if ( !((AppContext) getApplication()).isLogin() ) {
			Intent intent = new Intent(HistoryActivity.this, SigninActivity.class);
			intent.putExtra("page", 2);
			startActivity(intent);
			this.finish();
		} else {
			Intent intent = new Intent(HistoryActivity.this, SyncService.class);
			intent.setAction(SyncService.SYNC_SERVICE);
			startService(intent);
		}
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		registerReceiver();
	}

	private void registerReceiver() {
		ridingReceiver = new RidingReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(RidingService.UPDATE_STAT);
//		filter.addAction(RidingService.RL_UPDATE);
		registerReceiver(ridingReceiver, filter);
		
		IntentFilter filterSync = new IntentFilter();
		filterSync.addAction(SyncService.SYNC_OVER);
		filterSync.addAction(SyncService.SYNC_REFRESH);
		filterSync.addAction(SyncService.SYNC_ING);
		syncReceiver = new SyncReceiver();
		registerReceiver(syncReceiver, filterSync);
	}
	
	@Override
	protected void onStop() {
		Log.i(TAG, "--onStop--");
		if (ridingReceiver != null) {
			this.unregisterReceiver(ridingReceiver);
			this.unregisterReceiver(syncReceiver);
		}
		super.onStop();
	}
	
	public class RidingReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "---收到通知---");
			String action = intent.getAction();
			if (action.equals(RidingService.UPDATE_STAT)) {
				Log.i(TAG, "---UPDATE_STAT.通知---");
				if ( nowRidingLine == null ) {
					return ;
				}
				float totalMileage = intent.getFloatExtra("totalMileage", 0.00f);
				int totalPoint = intent.getIntExtra("totalPoint", 0);
				long totalTime = intent.getLongExtra("totalTime", 0l);
				
				nowRidingLine.setTotalMileage(totalMileage);
				nowRidingLine.setTotalPoint(totalPoint);
				nowRidingLine.setTotalTime(totalTime);
				nowRidingLine.setIsNow(true);
				tListAdapter.notifyDataSetChanged();
			} 
//			else if (action.equals(RidingService.RL_UPDATE)) {
////				long rlId = intent.getLongExtra("now_rlId", 0l);
//				
//				String act = intent.getStringExtra("act");
//				if ( "end".equals(act) ) {
//					loadLocalData();// 这里或许有更好的做法###
//				}
//			}
		}
	}
	
	public class SyncReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "---收到通知---");
			String action = intent.getAction();
			if ( action.equals(SyncService.SYNC_OVER) ) {
				if ( rotateAnimation != null ) {
					btnOK.clearAnimation();
				}
				loadLocalData(); // 这里或许有更好的做法###
			} else if ( action.equals(SyncService.SYNC_REFRESH) ) {
				loadLocalData(); // 这里或许有更好的做法###
			} else if ( action.equals(SyncService.SYNC_ING) ) {
				if ( rotateAnimation != null && btnOK.getAnimation() == null) {
					btnOK.startAnimation(rotateAnimation);
				}
			}
		}
	}
}
